<template>
  <div class="configuration-create-page">
    <el-scrollbar class="classify-scrollbar">
      <div class="create-title">个性化配置</div>
      <el-form ref="form" class="create-form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="是否需要签名" prop="isSign">
          <el-radio-group v-model="form.isSign">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否首页提醒" prop="isRemind">
          <el-radio-group v-model="form.isRemind">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-card v-if="form.isRemind === '1'" class="box-card">
          <div slot="header" class="clearfix">
            <span>首页提醒配置</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="handleView('preview')">预览</el-button>
          </div>
          <el-form-item label="模板选择" prop="remindType">
            <el-radio-group v-model="form.remindType" @change="changeType">
              <el-radio label="0">模板库选择</el-radio>
              <el-radio label="1">自定义</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.remindType === '0'" label="选择模板" prop="templateId">
            <el-select
              v-model="form.templateId"
              placeholder="请选择模板"
              clearable
              style="width: 75%;"
              @change="selectTemplate"
            >
              <el-option
                v-for="(item, index) in templateOptions"
                :key="index"
                :label="item.templateName"
                :value="item.id"
              />
            </el-select>&nbsp;&nbsp;
            <el-button type="primary" @click="handleView('template')">模板预览</el-button>
          </el-form-item>
          <template v-if="customShow">
            <el-form-item prop="remindImg">
              <el-row :gutter="10">
                <el-col :span="12">
                  <div class="add-image">
                    <div class="add-image-title">
                      <span>上传背景图片</span>
                    </div>
                    <image-upload
                      ref="upload4home"
                      :key="upload4area.imagecropperKey"
                      v-model="form.remindImg"
                      :preview-id="form.remindImg"
                      :forever="true"
                      :width="540"
                      :view="upload4area.view"
                      :height="500"
                      :no-circle="true"
                      :no-rotate="false"
                      lang-type="zh"
                    />
                  </div>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="按钮背景颜色" prop="buttonBGC">
              <el-color-picker v-model="form.buttonBGC" />
            </el-form-item>
            <el-form-item label="按钮文字颜色" prop="buttonBGW">
              <el-color-picker v-model="form.buttonBGW" />
            </el-form-item>
            <el-form-item label="提醒内容颜色" prop="contentColor">
              <el-color-picker v-model="form.contentColor" />
            </el-form-item>
          </template>
          <el-form-item label="提醒内容" prop="remindContent">
            <el-row>
              <el-col :span="18">
                <el-input
                  ref="textInput"
                  v-model="form.remindContent"
                  placeholder=""
                  type="textarea"
                  @input="handleInput"
                  @blur="handleInputBlur"
                />

              </el-col>
              <el-col :offset="1" :span="2">
                <el-dropdown trigger="click" style="margin-top: 10px;" size="small" @command="insertFlg">
                  <el-button type="primary" size="small">
                    插入变量<i class="el-icon-arrow-down el-icon--right" />
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-for="(item,i) in dict.FLGXHPZNR" :key="i" :command="item.dictValue">{{
                      item.dictName
                    }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="提醒频率" prop="frequency">
            <el-radio-group v-model="form.frequency">
              <el-radio label="1">仅提醒一次</el-radio>
              <el-radio label="2">每日提醒</el-radio>
              <el-radio label="3">每次登陆提醒</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item v-if="form.frequency==='1'" label="提醒时间设置" prop="receiveTime">
            <el-date-picker
              v-model="form.time"
              style="width:70%"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
              :disabled="fit"
            /> &nbsp;&nbsp;<el-checkbox v-model="fit" @change="setEqualTime">不限制</el-checkbox>
          </el-form-item>
        </el-card>
      </el-form>
      <div class="page-footer">
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </el-scrollbar>
    <preview
      v-if="previewStatus"
      :obj="previewObj"
      :type="previewType"
      @closeSet="previewStatus = false"
    />
  </div>
</template>

<script>
import preview from '../components/preview/index'
import { get, set, getTemplateOptions, getDictByCode } from '@/views/welfare/directional/api/config'

export default {
  name: 'Configuration',
  components: { preview },
  data() {
    return {
      form: {
        isSign: '0',
        isRemind: '0',
        remindType: '',
        remindImg: '',
        buttonBGC: '',
        buttonBGW: '',
        contentColor: '',
        remindContent: '',
        frequency: '',
        time: [],
        templateId: ''
      },
      rules: {
        isSign: [{
          required: true,
          message: '请选择是否需要签名',
          trigger: 'change'
        }],
        isRemind: [{
          required: true,
          message: '请选择是否首页提醒',
          trigger: 'change'
        }],
        remindType: [{
          required: true,
          message: '请选择提醒模板',
          trigger: 'change'
        }],
        buttonBGC: [{
          required: true,
          message: '请选择按钮背景颜色',
          trigger: 'change'
        }],
        buttonBGW: [{
          required: true,
          message: '请选择按钮文字颜色',
          trigger: 'change'
        }],
        frequency: [{
          required: true,
          message: '请选择提醒频率',
          trigger: 'change'
        }],
        templateId: [{
          required: true,
          message: '请选择模板',
          trigger: 'change'
        }],
        remindContent: [
          { required: true, message: '请输入提醒内容', trigger: 'blur' }
        ],
        contentColor: [{
          required: true,
          message: '请选择提醒内容颜色',
          trigger: 'change'
        }],
        remindImg: [{
          required: true,
          message: '请上传背景图片',
          trigger: 'change'
        }]
      },
      upload4area: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0
      },
      fit: false,
      id: '',
      templateVisible: false,
      blurIndex: null,

      previewStatus: false,
      previewType: '',
      previewObj: {},
      templateOptions: [], // 模板列表
      selectTemplateObj: {},
      templateIndex: '',
      dict: {
        FLGXHPZNR: [] //
      },
      customShow: false// 自定义模板显示
    }
  },
  async created() {
    this.templateOptions = await this.getTemplateOptions()
    this.dict.FLGXHPZNR = await this.getDict('FLGXHPZNR')
    if (this.$route.query.id) {
      this.id = this.$route.query.id
      this.getInfo()
    }
  },
  methods: {
    handleCancel() {
      this.$router.replace({
        path: this.$filterPath('index'),
        query: { t: this.$route.query.t }
      })
    },
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(response => {
          const arr = response.data.data[0].list || []
          resolve(arr)
        }).catch(error => {
          reject(error)
        })
      })
    },
    /**
     * 获取模板列表
     * */
    getTemplateOptions() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      var query = {
        templateBaseType: 'MBK_SYTX',
        page: 1,
        pageSize: 100
      }
      return new Promise((resolve, reject) => {
        getTemplateOptions(query).then(res => {
          loading.close()
          const arr = res.data.data.rows || []
          resolve(arr)
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    handleInput() {
      this.$forceUpdate()
    },
    insertFlg(flg) {
      const index = this.blurIndex || 0
      const str = this.form.remindContent || ''
      this.$refs.textInput.focus()
      if (index === 0) {
        this.form.remindContent = flg + str
        this.blurIndex = flg.length
      } else {
        this.form.remindContent = str.slice(0, index) + flg + str.slice(index)
      }
      this.$forceUpdate()
    },
    handleInputBlur(e) {
      this.blurIndex = e.srcElement.selectionStart
    },

    setEqualTime(e) {
      if (e) {
        this.form.time = []
      }
    },
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })

          const params = Object.assign({}, this.form)
          if (this.fit) {
            params['timeIntervalStart'] = ''
            params['timeIntervalEnd'] = ''
          } else {
            params['timeIntervalStart'] = params.time && params.time.length > 0 ? params.time[0] : ''
            params['timeIntervalEnd'] = params.time && params.time.length > 0 ? params.time[1] : ''
          }
          delete params['time']
          const obj = {
            id: this.id,
            personalizedConfig: JSON.stringify(params)
          }
          return new Promise((resolve, reject) => {
            set(obj).then(() => {
              loading.close()
              this.$message({
                title: '成功',
                message: '配置成功',
                type: 'success',
                duration: 2000
              })
              // this.$router.back()
              this.handleCancel()
            }).catch(error => {
              reject(error)
              loading.close()
            })
          })
        }
      })
    },
    /**
     * 选择模板
     * */
    selectTemplate(id) {
      this.selectTemplateObj = this.templateOptions.find(item => item.id === id)
      if (this.selectTemplateObj && this.selectTemplateObj.id) {
        try {
          if (this.selectTemplateObj.templateContent) {
            const templateContent = JSON.parse(this.selectTemplateObj.templateContent)
            this.form.remindImg = templateContent[0].content
            this.form.buttonBGC = templateContent[1].content
            this.form.buttonBGW = templateContent[2].content
            this.form.contentColor = templateContent[3].content
          }
        } catch (e) {
        }
      } else {
        this.form.templateId = ''
        this.form.remindImg = ''
        this.form.buttonBGC = '#FFFFFF'
        this.form.buttonBGW = '#FFFFFF'
        this.form.contentColor = '#FFFFFF'
      }
    },
    /**
     * 预览
     */
    handleView(type) {
      if (!this.form.remindImg || !this.form.buttonBGC || !this.form.buttonBGW || !this.form.contentColor) {
        this.$message({
          type: 'warning',
          message: '请先完成配置再预览'
        })
        return
      }
      this.previewObj = Object.assign({}, this.form)
      this.previewType = type
      this.previewStatus = true
    },
    /**
     * 获取配置详情
     * @returns {Promise<unknown>}
     */
    getInfo() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: this.id }).then(res => {
          loading.close()
          if (res.data.data) {
            const data = JSON.parse(res.data.data)
            for (const key in this.form) {
              if (key === 'time') {
                if (data['timeIntervalStart'] && data['timeIntervalEnd']) {
                  this.form[key] = [data['timeIntervalStart'], data['timeIntervalEnd']]
                } else {
                  this.fit = data.frequency === '1'
                  this.form[key] = []
                }
              } else {
                if (key === 'buttonBGC' || key === 'buttonBGW' || key === 'contentColor') {
                  this.form[key] = data[key] ? data[key] : '#FFFFFF'
                } else {
                  this.form[key] = data[key]
                }
              }
            }
            this.customShow = this.form.remindType === '1'
          }
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    /**
     *更改提醒模板时，清空
     */
    changeType() {
      this.form.templateId = ''
      this.form.remindImg = ''
      this.form.buttonBGC = '#FFFFFF'
      this.form.buttonBGW = '#FFFFFF'
      this.form.contentColor = '#FFFFFF'
      this.customShow = this.form.remindType === '1'
    }
  }
}
</script>

<style lang="scss">
.configuration-create-page {
  padding: 10px;

  .add-image {
    border: 1px solid #e5e5e5;
    padding: 0 20px 20px;
    border-radius: 4px;

    .add-image-title {
      display: flex;
      align-items: center;
      justify-content: space-between;

      & > span {
        color: #666;
        font-size: 14px;
      }
    }

    .add-image-main {
      display: inline-block;
      position: relative;
      background: #f7f7f8;
      border-radius: 4px;
      margin-bottom: 10px;

      .el-image {
        display: block;
      }

      &:hover {
        border-color: #fe5a61;
      }

      .icon-wrap {
        width: 300px;
        height: 180px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(247, 247, 248, 1);
        border: 1px solid rgba(226, 227, 232, 1);
        border-radius: 4px;

        .avatar-uploader-icon {
          font-size: 48px;
          color: #dadada;
          width: 300px;
          text-align: center;
        }
      }

      img {
        display: block;
        max-width: 400px;
        border-radius: 4px;
      }
    }
  }

  .classify-scrollbar {
    background-color: #fff;
    margin-top: 10px;

    .create-title {
      position: relative;
      height: 40px;
      line-height: 40px;
      padding: 0 20px;
      background-color: #ffffff;
      border-bottom: 1px solid #e5e5e5;
      font-family: PingFangSC-Medium;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
      font-size: 14px;

      &:before {
        content: "";
        position: absolute;
        width: 2px;
        @include bg-color($mainColor);
        top: 13px;
        bottom: 13px;
        left: 15px;
      }
    }

    .create-form {
      width: 1000px !important;
      margin: 20px auto 0;

      .el-select {
        width: 100%;
      }

      .form-btns {
        text-align: center;
      }
    }
  }

  .page-footer {
    padding: 10px 0;
    background-color: white;
    text-align: center;

    &:first-child {
      margin-right: 10px;
    }
  }
}
</style>
